package net.tngou.iask.action.my;


import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;


import net.tngou.iask.action.BaseAction;
import net.tngou.iask.jdbc.PageUtil;
import net.tngou.iask.pojo.POJO;
import net.tngou.iask.pojo.Role;
import net.tngou.iask.pojo.User;
import net.tngou.iask.service.UserService;

public class UserAction extends BaseAction {
	
	/**
	 * 成员列表
	 */
	public void list() {
		int role=(int) ask.getId();
		if((role==0||role==1||role==2||role==-1)&&!(user.getRole()==1||user.getRole()==2))
		{
			run_500();return;
		}
		
		if((role==3||role==4||role==5||role==6)&&!(user.getRole()==3||user.getRole()==4))
		{
			run_500();return;
		}
		
		UserService service = new UserService();
		PageUtil page = service.getPage(ask.getPage(), ask.getSize(), user.getMain(), role, ask.getKeyword());
		root.put("page", page);
		root.put("role", role);
		 root.put("list", getRole());
		root.put("keyword", ask.getKeyword());
		printFreemarker("my/user_list.ftl", root);
	}
	
	/**
	 * 添加成员
	 */
	public void add() {
		int role=(int) ask.getId();
		Role r = new Role().get(role);
		if(r==null) {run_404();return;}
		root.put("r", r);		
		root.put("role", role);
		printFreemarker("my/user_add.ftl", root);
	}
	public void change() {
		String[] params = request.getParams();
		int id=0;
		if(params!=null&&params.length>0&&NumberUtils.isNumber(params[0]))
		{	
			id=Integer.parseInt(params[0]);
		}
		if(id==0){run_404();return;}
		User u = new User().get(id);
		if(u==null){run_404();return;}
		Role r = new Role().get(u.getRole());
		if(r==null){run_404();return;}
		root.put("role", u.getRole());
		root.put("r", r);
		root.put("u", u);
		 root.put("list", getRole());
		printFreemarker("my/user_change.ftl", root);
	}
	public void init() {
		String[] params = request.getParams();
		int id=0;
		if(params!=null&&params.length>0&&NumberUtils.isNumber(params[0]))
		{	
			id=Integer.parseInt(params[0]);
		}
		if(id==0){run_404();return;}
		User u = new User().get(id);
		if(u==null){run_404();return;}
		Role r = new Role().get(u.getRole());
		if(r==null){run_404();return;}
		root.put("role", u.getRole());
		root.put("r", r);
		root.put("u", u);
		printFreemarker("my/user_init.ftl", root);
	}
	
	
	
	
	public List<Role> getRole() {
		 @SuppressWarnings("unchecked")
			List<Role> list = (List<Role>) service.getList(Role.class);
			 if(user.getRole()==1||user.getRole()==2)
			 {
				 for (int i = 0; i < list.size(); i++) {
					 Role r =list.get(i);
					 if(r.getId()==3||r.getId()==4||r.getId()==5||r.getId()==6)
					 {
							list.remove(i);i--;
					 }
				}
				
				 
			 }
			 if(user.getRole()==3||user.getRole()==4)
			 {
				 for (int i = 0; i < list.size(); i++) {
					 Role r =list.get(i);
					 if(r.getId()==1||r.getId()==2||r.getId()==0)
					 {
							list.remove(i);i--;
					 }
				}
			 }
			return list;
	}

}
